package io.rocketman.transport.channel.handler;

import io.rocketman.transport.NetworkTransportException;
import io.rocketman.transport.channel.Channel;

import java.net.InetSocketAddress;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author He Peng
 * @create 2018-05-25 3:08
 * @update 2018-05-25 3:08
 * @updatedesc : 更新说明
 * @see
 */
public abstract class AbstractChannelHandler implements ChannelHandler {

    private final Map<String , Channel> connectedChannel = new ConcurrentHashMap<String, Channel>();

    @Override
    public void channelClose(Channel channel) {
        removeChannel(channel);
    }

    @Override
    public void disconnect(Channel channel) {
        removeChannel(channel);
    }


    @Override
    public void connect(Channel channel) {
        this.connectedChannel.put(getChannelKey(channel) , channel);
    }


    @Override
    public void exceptionCaught(Channel channel, Throwable t) {
        channel.close();
    }

    private void removeChannel(Channel channel) {
        this.connectedChannel.remove(getChannelKey(channel));
    }


    private String getChannelKey(Channel channel) {
        String serviceKey;
        if (channel.getServerMetaData() != null) {
            serviceKey = channel.getServerMetaData().getServiceKey();
        } else if (channel.getClientMetaData() != null) {
            serviceKey = channel.getClientMetaData().getServiceKey();
        } else {
            throw new IllegalArgumentException("service metadata is null");
        }
        InetSocketAddress remoteAddress = channel.getRemoteAddress();
        InetSocketAddress localAddress = channel.getLocalAddress();
        return new StringBuilder(remoteAddress.getHostName())
                .append(":")
                .append(remoteAddress.getPort())
                .append("->")
                .append(localAddress.getHostName())
                .append(":")
                .append(localAddress.getPort())
                .append("-")
                .append(serviceKey)
                .toString();
    }
}
